package com.example.demo.control;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.confi.JenkinsConf;
import com.example.demo.others.jenkins.Jenkins;
import com.example.demo.util.HtmlUtil;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.BaseModel;
import com.offbytwo.jenkins.model.Job;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * Created by Administrator on 2017-6-9.
 */
@Controller
@RequestMapping
public class IndexControl {

    Logger logger = LoggerFactory.getLogger(IndexControl.class);


    @RequestMapping("/")
    public String index(Model v, HttpServletRequest request) {

        HttpSession session = request.getSession();


        if (LoginUtil.valid(request)) return "redirect:/tologin";


        logger.info("index ");

        v.addAttribute("list", JenkinsConf.list);
        return "index";
    }


    @RequestMapping("/index")
    public String index1(Model v, HttpServletRequest request) {

        HttpSession session = request.getSession();


        if (LoginUtil.valid(request)) return "redirect:/tologin";

        JenkinsServer jenkins = Jenkins.jenkins(SessionUtil.jenkinsname(request));

        try {

          Job job
             =jenkins.getJob("build-service");



        String s =  job.details().getFileFromWorkspace("");



            BaseModel b =   job.getClient().get("http://jenkins.dev-mycp.com/view/%E6%89%93%E5%8C%85-service2.0/job/build-service-job/build",BaseModel.class);


            List<JSONObject> list = new ArrayList<>();
            jenkins.getJobs().keySet().stream().filter(k -> !k.contains("(git)") && !k.contains("deploy"))
                    .forEach(k -> {
                        try {


                            logger.info(k + " " + jenkins.getJob(k).getUrl());

                            JSONObject j = new JSONObject();
                            j.put("key", k);
                            list.add(j);
                        }catch (Exception e){

                        }
                    });

            v.addAttribute("list", list);


        } catch (Exception e) {

            logger.info(e.getMessage());
        }
        logger.info("index ");

        return "index1";
    }


}
